#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
贵州茅台三种AI模型预测结果对比报告
"""

import matplotlib.pyplot as plt
import numpy as np
from pypinyin import lazy_pinyin

def chinese_to_pinyin(text):
    """将中文转换为拼音"""
    if any('\u4e00' <= char <= '\u9fff' for char in text):
        return ' '.join(lazy_pinyin(text)).title()
    return text

def create_comparison_report():
    """创建模型对比报告"""
    
    print("🍶 贵州茅台(600519) 三种AI模型预测对比报告")
    print("=" * 70)
    
    # 实际结果数据
    models_data = {
        'RandomForest': {
            'name': 'RandomForest (传统ML)',
            'current_price': 1472.66,
            'predicted_close': 1452.43,
            'change_percent': -1.37,
            'rmse': 121.06,
            'mae': 77.80,
            'params': '100棵树',
            'training_time': '~30秒',
            'prediction_quality': '合理',
            'color': 'blue'
        },
        'LSTM': {
            'name': 'LSTM (深度学习)',
            'current_price': 1483.00,
            'predicted_open': 1511.36,
            'predicted_close': 1516.46,
            'change_percent': +2.26,
            'rmse': 96.59,
            'mae': 66.50,
            'params': '14K参数',
            'training_time': '~2分钟',
            'prediction_quality': '合理',
            'color': 'green'
        },
        'Transformer': {
            'name': 'Stock-GPT (Transformer)',
            'current_price': 1483.00,
            'predicted_open': 14.28,
            'predicted_close': 124.18,
            'change_percent': -91.63,
            'rmse': 0.0,  # 数据有问题，无法计算
            'mae': 0.0,
            'params': '557K参数',
            'training_time': '~5分钟',
            'prediction_quality': '异常',
            'color': 'red'
        }
    }
    
    # 打印详细对比
    print("📊 详细预测结果对比")
    print("-" * 70)
    
    for model_key, data in models_data.items():
        print(f"\\n🤖 {data['name']}:")
        print(f"   📏 模型规模: {data['params']}")
        print(f"   ⏱️ 训练时间: {data['training_time']}")
        print(f"   💰 当前价格: {data['current_price']:.2f}元")
        
        if 'predicted_open' in data:
            print(f"   🌅 预测开盘: {data['predicted_open']:.2f}元")
        print(f"   🌇 预测收盘: {data['predicted_close']:.2f}元")
        print(f"   📈 预测涨跌: {data['change_percent']:+.2f}%")
        
        if data['rmse'] > 0:
            print(f"   🎯 RMSE误差: {data['rmse']:.2f}")
            print(f"   🎯 MAE误差: {data['mae']:.2f}")
        
        print(f"   ✅ 预测质量: {data['prediction_quality']}")
    
    # 创建可视化对比图
    create_comparison_chart(models_data)
    
    # 分析总结
    print("\\n🔍 分析总结")
    print("=" * 70)
    
    print("\\n✅ **成功的模型:**")
    print("1. 🥇 **LSTM** - 表现最佳")
    print("   • 预测合理 (+2.26%)")
    print("   • 误差最小 (RMSE: 96.59)")
    print("   • 既能预测开盘价又能预测收盘价")
    print("   • 训练稳定，结果可信")
    
    print("\\n2. 🥈 **RandomForest** - 表现良好")
    print("   • 预测保守 (-1.37%)")
    print("   • 训练速度最快")
    print("   • 传统可靠，易于解释")
    
    print("\\n❌ **问题模型:**")
    print("3. 🚨 **Stock-GPT Transformer** - 需要修复")
    print("   • 预测完全不合理 (-91.63%)")
    print("   • 价格预测值过小 (124.18元 vs 1483元)")
    print("   • 归一化/Token化存在严重问题")
    print("   • 需要重新调试数据预处理流程")
    
    print("\\n💡 **技术洞察:**")
    print("• **数据预处理的重要性**: Transformer失败主要因数据处理问题")
    print("• **模型复杂度 ≠ 效果**: 最复杂的模型表现最差")
    print("• **传统方法的价值**: LSTM和RandomForest都给出合理预测")
    print("• **时间序列的特殊性**: 股票数据需要专门的处理方式")
    
    print("\\n🎯 **投资建议综合:**")
    lstm_trend = "看涨" if models_data['LSTM']['change_percent'] > 0 else "看跌"
    rf_trend = "看涨" if models_data['RandomForest']['change_percent'] > 0 else "看跌"
    
    print(f"• LSTM模型: {lstm_trend} {models_data['LSTM']['change_percent']:+.2f}%")
    print(f"• RandomForest: {rf_trend} {models_data['RandomForest']['change_percent']:+.2f}%")
    print("• **综合判断**: 两个可靠模型观点分歧，建议谨慎操作")
    print("• **操作策略**: 可考虑少量试探性买入，设好止损位")

def create_comparison_chart(models_data):
    """创建模型预测对比图表"""
    
    # 设置中文字体
    plt.rcParams['font.family'] = ['DejaVu Sans']
    
    # 准备数据
    models = []
    predictions = []
    colors = []
    current_prices = []
    
    for model_key, data in models_data.items():
        if data['prediction_quality'] != '异常':  # 排除异常数据
            models.append(data['name'])
            predictions.append(data['predicted_close'])
            colors.append(data['color'])
            current_prices.append(data['current_price'])
    
    # 创建图表
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
    
    # 图1: 预测价格对比
    bars = ax1.bar(models, predictions, color=colors, alpha=0.7)
    ax1.axhline(y=np.mean(current_prices), color='black', linestyle='--', 
                label=f'{chinese_to_pinyin("当前价格")}: {np.mean(current_prices):.0f}')
    
    ax1.set_title(f'{chinese_to_pinyin("贵州茅台价格预测对比")}', fontsize=14, fontweight='bold')
    ax1.set_ylabel(f'{chinese_to_pinyin("价格")} (yuan)')
    ax1.legend()
    ax1.grid(True, alpha=0.3)
    
    # 在柱状图上显示数值
    for bar, pred in zip(bars, predictions):
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                f'{pred:.0f}', ha='center', va='bottom')
    
    # 图2: 预测涨跌幅对比
    changes = []
    model_names = []
    bar_colors = []
    
    for model_key, data in models_data.items():
        if data['prediction_quality'] != '异常':
            changes.append(data['change_percent'])
            model_names.append(data['name'])
            color = 'green' if data['change_percent'] > 0 else 'red'
            bar_colors.append(color)
    
    bars2 = ax2.bar(model_names, changes, color=bar_colors, alpha=0.7)
    ax2.axhline(y=0, color='black', linestyle='-', alpha=0.5)
    ax2.set_title(f'{chinese_to_pinyin("预测涨跌幅对比")}', fontsize=14, fontweight='bold')
    ax2.set_ylabel(f'{chinese_to_pinyin("涨跌幅")} (%)')
    ax2.grid(True, alpha=0.3)
    
    # 在柱状图上显示数值
    for bar, change in zip(bars2, changes):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                f'{change:+.1f}%', ha='center', 
                va='bottom' if height > 0 else 'top')
    
    plt.tight_layout()
    
    # 保存图表
    output_file = 'maotai_model_comparison.png'
    plt.savefig(output_file, dpi=300, bbox_inches='tight', facecolor='white')
    print(f"\\n📈 对比图表已保存: {output_file}")
    
    plt.close()

if __name__ == "__main__":
    create_comparison_report()